package cn.edu.scau.cmi.ema.service;

import cn.edu.scau.cmi.ema.base.CmiPagination;
import cn.edu.scau.cmi.ema.domain.Discoverylink;
import cn.edu.scau.cmi.ema.domain.Event;
import cn.edu.scau.cmi.ema.service.base.CmiEmaService;
import cn.edu.scau.cmi.ema.util.CmiSqlUtil;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.Query;
import java.util.*;
@Service("DiscoverylinkService")
@Transactional

public class DiscoverylinkServiceImpl extends CmiEmaService implements DiscoverylinkService {
	public DiscoverylinkServiceImpl() {
	}

	@Transactional
	public Discoverylink saveDiscoverylink(Discoverylink discoverylink) {
		Set<Event> existingEventsForEvent = new HashSet<Event>();

		Set<Event> selectedEventsForEvent = discoverylink.getEventsForDiscoverylink();

		if (discoverylink.getId() == null) {

			Discoverylink existingDiscoverylink = discoverylinkDAO
					.findDiscoverylinkByPhysicalPrimaryKey(discoverylink.getName());

			if (isEquals(discoverylink, existingDiscoverylink)) {
				return existingDiscoverylink;
			}

			discoverylink = discoverylinkDAO.store(discoverylink);
			discoverylinkDAO.flush();

			for (Event relatedEvent : selectedEventsForEvent) {
				relatedEvent.getDiscoverylinksForEvent().add(discoverylink);
				eventDAO.store(relatedEvent);
			}
		} else {
			Discoverylink existingDiscoverylink = discoverylinkDAO.findDiscoverylinkByPrimaryKey(discoverylink.getId());

			existingEventsForEvent = existingDiscoverylink.getEventsForDiscoverylink();

			Set<Event> prepareDeleteEventsForEvent = new HashSet<Event>();
			Set<Event> prepareAddEventsForEvent = new HashSet<Event>();

			prepareDeleteEventsForEvent.addAll(selectedEventsForEvent);
			prepareDeleteEventsForEvent.addAll(existingEventsForEvent);

			prepareAddEventsForEvent.addAll(selectedEventsForEvent);
			prepareAddEventsForEvent.addAll(existingEventsForEvent);

			prepareDeleteEventsForEvent.removeAll(selectedEventsForEvent);
			prepareAddEventsForEvent.removeAll(existingEventsForEvent);

			for (Event relatedEvent : prepareAddEventsForEvent) {

				relatedEvent.getDiscoverylinksForEvent().add(existingDiscoverylink);
				eventDAO.store(relatedEvent);
			}

			for (Event relatedEvent : prepareDeleteEventsForEvent) {

				relatedEvent.getDiscoverylinksForEvent().remove(existingDiscoverylink);
				eventDAO.store(relatedEvent);
			}
			discoverylink = discoverylinkDAO.store(discoverylink);
			discoverylinkDAO.flush();
		}

		eventDAO.flush();
		return discoverylink;
	}

	public void deleteDiscoverylink(Discoverylink discoverylink) {
		discoverylinkDAO.remove(discoverylink);
		discoverylinkDAO.flush();
	}

	@Transactional
	public void deleteDiscoverylinks(Set<Integer> deleteDiscoverylinksId) {
		Query query = discoverylinkDAO.createNamedQuery("deleteDiscoverylinksById", -1, -1);
		query.setParameter(1, deleteDiscoverylinksId);
		query.executeUpdate();
	}

	@Transactional
	public Set<Discoverylink> loadDiscoverylinks() {
		return discoverylinkDAO.findAllDiscoverylinks();

	}

	@Transactional
	public Set<Discoverylink> loadReferenceDiscoverylinks(Set<Discoverylink> discoverylinks) {
		Iterator<Discoverylink> discoverylinksIterator = discoverylinks.iterator();
		Set<Discoverylink> referencedDiscoverylinks = new HashSet<>();
		while (discoverylinksIterator.hasNext()) {
			Discoverylink currentDiscoverylink = discoverylinksIterator.next();

			if (!currentDiscoverylink.getEventsForDiscoverylink().isEmpty()) {
				referencedDiscoverylinks.add(currentDiscoverylink);
				continue;
			}
		}
		return referencedDiscoverylinks;
	}

	public Set<Discoverylink> loadDiscoverylinksByIdSet(Set<Integer> discoverylinkIdSet) {

		Iterator<Integer> discoverylinkIdIterator = discoverylinkIdSet.iterator();
		Set<Discoverylink> discoverylinkSet = new HashSet<>();
		while (discoverylinkIdIterator.hasNext()) {
			Integer id = discoverylinkIdIterator.next();
			Discoverylink currentDiscoverylink = discoverylinkDAO.findDiscoverylinkById(id);
			discoverylinkSet.add(currentDiscoverylink);
		}
		return discoverylinkSet;
	}

	@Transactional
	public List<Discoverylink> findAllDiscoverylinks(Integer startResult, Integer maxRows) {
		return new java.util.ArrayList<Discoverylink>(discoverylinkDAO.findAllDiscoverylinks(startResult, maxRows));
	}

	@Transactional
	public Discoverylink findDiscoverylinkByPrimaryKey(Integer id) {
		return discoverylinkDAO.findDiscoverylinkByPrimaryKey(id);
	}

	@Transactional
	public Integer countDiscoverylinks() {
		return ((Long) discoverylinkDAO.createQuerySingleResult("select count(o) from Discoverylink o")
				.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countDiscoverylinks(CmiPagination page) {
		String sql = CmiSqlUtil.createCountHql(page, Discoverylink.class);
		return ((Long) discoverylinkDAO.createQuerySingleResult(sql).getSingleResult()).intValue();
	}

	/**
	 * search for name with ajax
	 *
	 */
	@Transactional
	public Integer countDiscoverylinksByName(String queryName) {
		Query query = discoverylinkDAO.createNamedQuery("countDiscoverylinksByName", -1, -1);
		query.setParameter(1, queryName);
		return new Long((long) query.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countDiscoverylinksByDetachedCriteria(CmiPagination page) {
		DetachedCriteria detachedCriteria = CmiSqlUtil.createDetachedCriteria(page, Discoverylink.class);
		Session session = (Session) entityManager.getDelegate();
		detachedCriteria.setProjection(Projections.rowCount());
		return new Long((long) detachedCriteria.getExecutableCriteria(session).uniqueResult()).intValue();
	}

	public Map<String, ?> loadDiscoverylinkObjectReferencedSet(Discoverylink discoverylink) {
		HashMap<String, Object> objectReferencedSetMap = new HashMap<>();

		Set<Integer> eventsIds = new HashSet<Integer>();
		for (Event event : discoverylink.getEventsForDiscoverylink()) {
			eventsIds.add(event.getId());
		}
		objectReferencedSetMap.put("eventsIds", eventsIds);

		return objectReferencedSetMap;
	}

	public Map<String, ?> loadDiscoverylinkClassReferencedSet(Discoverylink discoverylink) {
		HashMap<String, Object> classReferencedSetMap = new HashMap<>();
		classReferencedSetMap.put("events", eventDAO.findAllEvents());

		return classReferencedSetMap;
	}

	public boolean isEquals(Discoverylink discoverylink, Object obj) {
		if (obj == discoverylink)
			return true;
		if (!(obj instanceof Discoverylink))
			return false;
		Discoverylink comparedDiscoverylink = (Discoverylink) obj;
		if (!CheckPropertyEqual(discoverylink.getName(), comparedDiscoverylink.getName())) {
			return false;
		}
		return true;
	}

	public static <T> boolean CheckPropertyEqual(T originProperty, T comparedProperty) {
		// 基本类型经过参数传递后会自动装箱
		String[] className = originProperty.getClass().getName().split("\\.");
		if (className[0].equals("java") && className[1].equals("math")) {
			return ((Comparable) originProperty).compareTo(comparedProperty) == 0 ? true : false;
		} else {
			return originProperty.equals(comparedProperty);
		}
	}
}

